package com.ruoyi.web.controller.dc;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ExecUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SseEmitterUtils;
import com.ruoyi.common.utils.biz.BizModule;
import com.ruoyi.common.utils.biz.PathUtil;
import com.ruoyi.common.utils.biz.ResultSaveModule;
import com.ruoyi.web.vo.CorrectCoefficientModelVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * <p>
 *  动态修正系数建模预报
 * </p>
 *
 * @author liuhl
 * @since 2024-05-20
 */
@RestController
@RequestMapping("/correctCoeModel")
@AllArgsConstructor
@Slf4j
@Api(tags = "动态修正系数建模预报")
public class CorrectCoefficientModelController {



    @GetMapping("/height")
    @ApiOperation(value = "根据时间获取高度范围信息", notes = "根据时间获取高度范围信息", httpMethod = "GET")
    public AjaxResult height(CorrectCoefficientModelVo vo) {

        String codePath = PathUtil.codeModuleDir(BizModule.MODEL_CORRECT) + PathUtil.moduleDirs().getModelCorrect().get("height");

        //python3 get_height_by_time.py 2004-05-06 2004-05-12

        String command = "python "+codePath+" "+vo.getStartTime()+" "+vo.getEndTime();
        String results = ExecUtil.execCmdWithResult(command);
        if (results == null || !results.contains("###")){
            return AjaxResult.error(results);
        }
        String[] heightRange = results.split("###")[1].split("km");
        List<String> heightList = Arrays.asList(heightRange).stream().map(String::trim).collect(Collectors.toList());

        return AjaxResult.success(heightList);

    }

    @GetMapping("/coe")
    @ApiOperation(value = "根据修正时间范围和高度范围获取日志信息", notes = "根据修正时间范围和高度范围获取日志信息", httpMethod = "GET")
    public AjaxResult coe(CorrectCoefficientModelVo vo) {

        String codePath = PathUtil.codeModuleDir(BizModule.MODEL_CORRECT) + PathUtil.moduleDirs().getModelCorrect().get("coe");

        //python3 get_coe_file_by_time_height.py 2004-05-02 2004-05-05 439 537
        String[] split = vo.getHeight().split("~");
        String command = "python "+codePath+" "+vo.getStartTime()+" "+ vo.getEndTime() +" "+ split[0] + " "+ split[1];
        String results = ExecUtil.execCmdWithResult(command);
        if (results == null || !results.contains("###")){
            return AjaxResult.error(results);
        }
        String result = results.split("###")[1];
        return AjaxResult.success("", result);
    }

    @GetMapping("/build")
    @ApiOperation(value = "构建预报模型", notes = "构建预报模型", httpMethod = "GET")
    public AjaxResult build(CorrectCoefficientModelVo vo) {
        String name = "coe_build";
        String codePath = PathUtil.codeModuleDir(BizModule.MODEL_CORRECT) + PathUtil.moduleDirs().getModelCorrect().get("coe_build");
        String tmpTxtPath = PathUtil.tmpModuleDir(BizModule.MODEL_CORRECT) + "/" + name + System.currentTimeMillis() + ".txt";

        //f107kpdst，从前往后排列，必须是 f107 》 kp 》dst
        String[] indexArr = vo.getIndex().split(",");
        String indexParam = "";
        List<String> indexList = Arrays.asList(indexArr);
        if (indexList.contains("f107")){
            indexParam += "f107";
        }
        if (indexList.contains("kp")){
            indexParam += "kp";
        }
        if (indexList.contains("dst")){
            indexParam += "dst";
        }

        //python3 coefficient_predict_build.py f107kpdst 2004-05-02 2004-05-05 439 537 ./a.txt
        String[] split = vo.getHeight().split("~");
        String command = "python "+codePath+" "+indexParam+" "+vo.getStartTime()+" "+ vo.getEndTime() +" "+ split[0] + " "+ split[1] +" "+tmpTxtPath+" "+vo.getFrequence();
        String results = ExecUtil.execCmdWithResult(command);
        if (results == null || !results.contains("###")){
            return AjaxResult.error(results);
        }
        String jsonStr = results.split("###")[1];
        Map<String,Object> resultMap = JSONUtil.toBean(jsonStr, LinkedHashMap.class);
        //移除 timespan 字样,该字样是 计算频率
        resultMap.remove("timespan");

        resultMap.put("txtPath",tmpTxtPath);
        return AjaxResult.success(resultMap);

    }

    @GetMapping("/predict")
    @ApiOperation(value = "修正系数预报", notes = "修正系数预报", httpMethod = "GET")
    public AjaxResult predict(CorrectCoefficientModelVo vo) {

        String codePath = PathUtil.codeModuleDir(BizModule.MODEL_CORRECT) + PathUtil.moduleDirs().getModelCorrect().get("coe_predict");

        //python3 coefficient_predict.py 2003-05-01 2003-05-07 ./a.txt
        String command = "python "+codePath+" "+vo.getStartTime()+" "+ vo.getEndTime() +" "+ vo.getTxtPath();
        String results = ExecUtil.execCmdWithResult(command);
        if (results == null || !results.contains("###")){
            return AjaxResult.error(results);
        }
        String jsonStr = results.split("###")[1];
        Map<String, Object> resultMap = null;
        try {
            resultMap =  JSONUtil.toBean(jsonStr, LinkedHashMap.class);
        }catch (Exception e) {
            return AjaxResult.error(jsonStr);
        }



        String savePath = PathUtil.outputModuleDir(BizModule.MODEL_CORRECT)
                + "/predict_result"
                + "/" + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_FORMAT)
                + "_" + IdUtil.simpleUUID() + ".txt";

        File file = new File(savePath);
        if (file.exists()) {
            file.delete();
        }
        FileWriter.create(file).write(JSONUtil.toJsonPrettyStr(resultMap));

        resultMap.put("resultData", JSONUtil.toJsonStr(Stream.of(savePath).collect(Collectors.toList())));
        resultMap.put("module", ResultSaveModule.MODEL_CORRECT);
        resultMap.put("submodule", ResultSaveModule.MODEL_CORRECT_PREDICT);

        //移除 timespan 字样,该字样是 计算频率
        resultMap.remove("timespan");

        return AjaxResult.success(resultMap);
    }


    @ApiOperation(value = "建立连接", notes = "建立连接")
    @GetMapping(path = "subscribe", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public SseEmitter push(String id, String flag) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return SseEmitterUtils.connect(id+loginUser.getUsername(), flag);
    }



}
